'use strict';

const Controller = require('egg').Controller;

class ClassController extends Controller {
    // 列表
    async index() {
        const { ctx, app } = this;

        let data = await ctx.model.Class.findAll({
            order: [
                ['order', 'ASC']
            ],
        })

        await ctx.renderTemplate({
            title: "年级列表",
            tempType: "table",
            table: {
                // 按钮
                buttons: {
                    // 新增操作
                    add: "/admin/class/create"
                },
                // 表头
                columns: [{
                    title: "ID",
                    fixed: 'center',
                    key: "id"
                }, {
                    title: "班级",
                    fixed: 'left',
                    render(item) {
                        let image = item.image ? item.image : '/public/assets/img/profiles/avatar-03.jpg'
                        return `
                        <h2 class="table-avatar">
                            <a href="">${item.name}</a>
                        </h2>
                        `
                    }
                }, {
                    title: "排序",
                    fixed: 'center',
                    key: "order"
                }, {
                    title: "创建时间",
                    fixed: 'center',
                    width: 180,
                    key: "created_time"
                }, {
                    title: "操作",
                    width: 200,
                    fixed: 'center',
                    action: {
                        edit: function (id) {
                            return `/admin/class/edit/${id}`
                        },
                        delete: function (id) {
                            return `/admin/class/delete/${id}`
                        },
                    }
                }]
            },
            data
        })
    }
    // 创建表单
    async create() {
        const { ctx } = this;
        await ctx.renderTemplate({
            // 页面标题
            title: "创建班级",
            // 模板类型 form表单，table表格分页
            tempType: "form",
            // 表单配置
            form: {
                // 提交地址
                action: "/admin/class",
                // 字段配置
                fields: [{
                    label: "班级名称",
                    type: "text",
                    name: "name",
                    placeholder: "班级名称"
                }, {
                    label: "排序",
                    type: "number",
                    name: "order",
                    placeholder: "排序"
                }]
            },
            // 新增成功跳转路径
            successUrl: "/admin/class"
        });
    }

    // 创建逻辑
    async save() {
        const { ctx, app } = this;

        ctx.validate({
            name: {
                type: "string",
                required: true,
                desc: "班级名称"
            },
            order: {
                type: "int",
                required: false,
                defValue: 0,
                desc: "排序"
            },
        })

        let { name, order } = ctx.request.body;

        let res = await app.model.Class.create({
            name, order
        })

        ctx.apiSuccess(res)
    }

    // 编辑表单页
    async edit() {
        const { ctx, app } = this
        const id = ctx.params.id

        let data = await app.model.Class.findOne({
            where: {
                id
            }
        })
        if (!data) {
            return await ctx.pageFail('该记录不存在')
        }

        data = JSON.parse(JSON.stringify(data))

        await ctx.renderTemplate({
            id,
            title: "修改班级",
            tempType: "form",
            form: {
                // 提交地址
                action: "/admin/class/" + id,
                // 字段配置
                fields: [{
                    label: "班级名称",
                    type: "text",
                    name: "name",
                    placeholder: "班级名称"
                }, {
                    label: "排序",
                    type: "number",
                    name: "order",
                    placeholder: "排序"
                }],
                // 默认值
                data
            },
            // 修改成功跳转路径
            successUrl: "/admin/class"
        })
    }

    // 更新逻辑
    async update() {
        const { ctx, app } = this;
        ctx.validate({
            id: {
                type: "int",
                required: true
            },
            name: {
                type: "string",
                required: true,
                desc: "班级名称"
            },
            order: {
                type: "int",
                required: true,
                defValue: 0,
                desc: "排序"
            },
        })

        let id = ctx.params.id
        let { name, order } = ctx.request.body

        let classes = await app.model.Class.findOne({
            where: {
                id
            }
        })
        if (!classes) {
            return ctx.apiFail('该记录不存在')
        }

        classes.name = name
        classes.order = order

        ctx.apiSuccess(await classes.save())

    }

    // 删除
    async delete() {
        const { ctx, app } = this;
        const classId = ctx.params.id;
        // 根据班级 ID 查询班级信息
        const classes = await ctx.model.Class.findByPk(classId, { include: ctx.model.Student });

        if (!classes) {
            ctx.status = 404;
            ctx.body = '班级不存在';
            return;
        }
        // 删除成绩表中与该班级相关的记录
        await app.model.Score.destroy({
            where: {
                classId
            }
        })
        // 解除班级与学生之间的关联（将学生的班级外键置为 NULL）
        await ctx.model.Student.update({ classId: 0 }, { where: { classId } });

       // 删除班级
    await classes.destroy();

    ctx.status = 200;
    ctx.body = '删除班级成功';
    }
}

module.exports = ClassController;
